<template>
  <div class="role">
    <!-- 添加角色 -->
    <div class="add-role">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="dialogVisible = true"
        >添加角色</el-button
      >
      <!-- 添加角色信息框 -->
      <div class="add-dialog">
        <el-dialog
          title="添加角色"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
        >
          <el-form :model="newForm" ref="addForm" :rules="rules">
            <el-form-item
              label="角色名字"
              :label-width="formLabelWidth"
              prop="roleName"
            >
              <el-input
                v-model="newForm.roleName"
                autocomplete="off"
              ></el-input> </el-form-item
            ><el-form-item label="备注" :label-width="formLabelWidth">
              <el-input v-model="newForm.remark" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色号码" :label-width="formLabelWidth">
              <el-input
                v-model="newForm.roleCode"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item label="是否禁用" :label-width="formLabelWidth">
              <el-switch v-model="newForm.isDeleted"></el-switch>
            </el-form-item>
            <el-form-item label="创建时间" :label-width="formLabelWidth">
              <el-date-picker
                v-model="newForm.gmtCreate"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="修改时间" :label-width="formLabelWidth">
              <el-date-picker
                v-model="newForm.gmtModified"
                type="datetime"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth">
              <el-button type="primary" @click="onSubmit('addForm')"
                >提交</el-button
              >
              <el-button @click="resetForm('addForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false"
            >确 定</el-button
          >
        </span> -->
        </el-dialog>
      </div>
    </div>
    <!-- 搜索 -->
    <div class="top-search">
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="search.roleName" placeholder="角色姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 内容展示 -->
    <div class="mid-container">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="id" label="角色编号"> </el-table-column>
        <el-table-column prop="roleName" label="角色姓名"> </el-table-column>
        <el-table-column prop="roleCode" label="备注"> </el-table-column>
        <el-table-column prop="remark" label="拥有权限"> </el-table-column>
        <el-table-column prop="isDeleted" label="是否禁用">
          <template slot-scope="scope">
            {{ scope.row.isDeleted ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
        <el-table-column prop="gmtModified" label="修改时间"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="changeRow(scope.$index, tableData)"
              type="text"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              @click="assignPermissions(scope.row.id)"
              type="text"
              size="small"
            >
              分配权限
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.$index, tableData)"
              type="text"
              size="small"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 分配权限弹出框 -->
    <div>
      <el-dialog
        title="提示"
        :visible.sync="dialogPermissionVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-tree
          ref="tree"
          default-expand-all
          :data="treeData"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkIds"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogPermissionVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPermission">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Menu from '@/api/menuAPI'
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 2,
      total: 0,
      tableData: [],
      search: {
        beginDate: '',
        endDate: '',
        roleName: '',
      },
      pages: 0,
      // 表单弹出框
      dialogVisible: false,
      // 分配权限弹出框
      dialogPermissionVisible: false,
      newForm: {},
      //控制表单元素与左侧框的距离
      formLabelWidth: '120px',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 15,
            message: '长度在 1 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 权限树
      treeData: [],
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children',
      },
      checkIds: [],
      rid: 0,
    }
  },
  methods: {
    //提交权限的修改
    async submitPermission() {
      //1.获取到已经勾选的节点id值
      //获取全选节点的数组
      let ids1 = this.$refs.tree.getCheckedKeys()
      //获取半选节点的数组
      let ids2 = this.$refs.tree.getHalfCheckedKeys()
      //把半选节点放前边   全选节点放后边
      let { data } = await Menu.submitPermission(this.rid, [...ids2, ...ids1])
      let { code, msg } = data
      if (code === 2000) {
        this.$message.success(msg)
        //关闭弹出框
        this.dialogPermissionVisible = false
      } else {
        this.$message.error(msg)
      }
    },
    // 分配权限
    async assignPermissions(rid) {
      this.rid = rid
      this.dialogPermissionVisible = true
      let { data } = await Menu.findPermessionByRoleId(rid)
      let { checkIds, treeData } = data.data
      this.treeData = treeData
      this.checkIds = checkIds
      this.$nextTick(() => {
        checkIds.forEach((key) => {
          this.$refs.tree.setChecked(key, true)
        })
      })
    },
    getter() {
      this.$http({
        method: 'post',
        url: `/role/findRole/${this.currentPage}/${this.pageSize}`,
        data: this.search,
      }).then((res) => {
        let { data } = res.data
        let { pages, total, records } = data
        this.pages = pages
        this.tableData = records
        this.total = total
      })
    },
    changeRow(index, rows) {
      console.log(rows)
      if (rows[index].id !== '1') {
        this.dialogVisible = true
        this.newForm = rows[index]
        this.$http({
          method: 'put',
          url: '/role',
          data: this.newForm,
        }).then((res) => {
          console.log(res)
        })
      } else {
        this.$message.error('没有权限')
      }
    },
    deleteRow(index, rows) {
      if (rows[index].id !== '1') {
        this.$http({
          method: 'DELETE',
          url: `/role/${rows[index].id}`,
        }).then((res) => {
          console.log(res)
          let { code, msg } = res.data
          if (code === 2000) {
            this.$message.success(msg)
          } else {
            this.$message.error(msg)
          }
        })
        rows.splice(index, 1)
      } else {
        this.$message.error('没有权限')
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getter()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getter()
    },
    onSearch() {
      this.currentPage = 1
      this.getter()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.newForm = {}
          done()
        })
        .catch((_) => {})
    },
    onSubmit() {
      this.$http({
        method: 'POST',
        url: '/role',
        data: this.newForm,
      }).then((res) => {
        console.log(res)
        let { code, data, msg } = res.data
        if (code === 2000) {
          this.$message.success(msg)
        } else {
          this.$message.error(msg)
        }
        this.getter()
        this.newForm = {}
      })
      this.dialogVisible = false
    },
    resetForm() {
      this.newForm = {}
    },
  },
  mounted() {
    this.getter()
  },
}
</script>

<style lang="less" scope>
.el-main {
  text-align: left !important;
}
.add-role,
.top-search {
  float: left;
}
.top-search {
  margin-left: 10px;
}
.el-date-editor.el-input {
  width: 80%;
}
.add-dialog {
  .el-input {
    width: 80%;
  }
}
</style>
